package com.saifan.wyy_ov.ui.communitycenter;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;

import com.saifan.wyy_ov.ui.communitycenter.PrefsConsts;

/**
 * 安装下载接收器
 * <p>
 * Created by wangchenlong on 16/1/5.
 */
public class InstallReceiver extends BroadcastReceiver {

    private static final String TAG =
            "DEBUG-WCL: " + InstallReceiver.class.getSimpleName();

    // 安装下载接收器
    @Override public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, downloadApkId);
        }
    }

    // 安装Apk
    private void installApk(Context context, long downloadApkId) {
        // 获取存储ID
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        long id = sp.getLong(PrefsConsts.DOWNLOAD_APK_ID_PREFS, -1L);
        try {

            if (downloadApkId == id) {
                DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadApkId);
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_VIEW);
                if (downloadFileUri != null) {
                    intent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                    context.startActivity(intent);
                } else {
                    Log.e(TAG, "下载失败");
                }
            }
        }catch ( Exception e){

            e.printStackTrace();
        }


    }
}